package com.qianlou.controller;


import com.qianlou.common.constant.BaseConstant;
import com.qianlou.common.enums.ResponseStatusEnum;
import com.qianlou.common.result.BaseResponse;
import com.qianlou.common.utils.JsonUtils;
import com.qianlou.common.utils.RedisOperator;
import com.qianlou.pojo.Candidate;
import com.qianlou.pojo.bo.VerifySMSBO;
import com.qianlou.pojo.vo.CandidateVO;
import com.qianlou.pojo.vo.EmailVo;
import com.qianlou.pojo.vo.InitQuestionsVO;
import com.qianlou.service.*;
import com.qianlou.common.utils.VerificationCodeGenerator;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/welcome")
public class WelcomeController {

    @Resource
    private CandidateService candidateService;

    @Resource
    private QuestionLibService questionLibService;

    @Resource
    private InterviewRecordService interviewRecordService;

    @Resource
    private EmailService emailService;

    @Resource
    private RedisOperator redisOperator;

    @PostMapping("/getSMSCode")
    public BaseResponse getSMSCode(@RequestParam("mobile") String mobile) {
        Candidate candidate = candidateService.getByMobile(mobile);
        if (candidate == null) {
            return BaseResponse.errorCustom(ResponseStatusEnum.USER_INFO_NOT_EXIST_ERROR);
        }
        String verificationCode = VerificationCodeGenerator.randomDigitsCode(6);
        emailService.send(EmailVo.builder()
                        .receivers(Collections.singletonList(candidate.getEmail()))
                        .subject("候选人登录验证码")
                        .content("验证码：" + verificationCode)
                .build());
        String smsCodeKey = BaseConstant.MOBILE_SMSCODE + ":" + mobile;
        redisOperator.set(smsCodeKey, verificationCode, 60L);
        return BaseResponse.ok();
    }

    @PostMapping("/verify")
    public BaseResponse verify(@RequestBody @Valid VerifySMSBO verifySMSBO) {
        String smsCode = verifySMSBO.getSmsCode();
        String smsCodeKey = BaseConstant.MOBILE_SMSCODE + ":" + verifySMSBO.getMobile();
        String redisSmsCode = redisOperator.get(smsCodeKey);
        if (StringUtils.isBlank(redisSmsCode) || !redisSmsCode.equals(smsCode)) {
            return BaseResponse.errorCustom(ResponseStatusEnum.SMS_CODE_ERROR);
        }
        //检查候选人是否存在
        Candidate candidate = candidateService.getByMobile(verifySMSBO.getMobile());
        if (candidate == null) {
            return BaseResponse.errorCustom(ResponseStatusEnum.USER_INFO_NOT_EXIST_ERROR);
        }
        //检查候选人是否已经面试过
        boolean existRecord = interviewRecordService.existRecordByCandidateId(candidate.getId());
        if (existRecord) {
            return BaseResponse.errorCustom(ResponseStatusEnum.USER_ALREADY_DID_INTERVIEW_ERROR);
        }
        CandidateVO candidateVO = new CandidateVO();
        BeanUtils.copyProperties(candidate, candidateVO);
        candidateVO.setCandidateId(candidate.getId());

        String uToken = UUID.randomUUID().toString();
        redisOperator.set(BaseConstant.REDIS_USER_INFO + ":" + candidate.getId(), uToken, 3 * 60 * 60L);
        redisOperator.del(smsCodeKey);
        redisOperator.set(BaseConstant.REDIS_USER_TOKEN + ":" + candidate.getId(),
                JsonUtils.objectToJson(candidateVO), 3 * 60 * 60L);
        return BaseResponse.ok(candidateVO);
    }

    @GetMapping("/prepareQuestion")
    public BaseResponse prepareQuestion(@RequestParam("candidateId") String candidateId) {
        String candidateInfo = redisOperator.get(BaseConstant.REDIS_USER_INFO + ":" + candidateId);
        String userToken = redisOperator.get(BaseConstant.REDIS_USER_TOKEN + ":" + candidateId);
        if (StringUtils.isBlank(candidateInfo) || StringUtils.isBlank(userToken)) {
            return BaseResponse.errorCustom(ResponseStatusEnum.USER_INFO_NOT_EXIST_ERROR);
        }
        List<InitQuestionsVO> questions = questionLibService.getRandomQuestions(candidateId, 10);
        if (CollectionUtils.isEmpty(questions)) {
            return BaseResponse.errorCustom(ResponseStatusEnum.QUESTION_NOT_EXIST_ERROR);
        }
        return BaseResponse.ok(questions);
    }
}
